using Android.Content;
using MauiBuilder.Services;
using AndroidX.Core.Content;
using AndroidX.Core.App;
using Android;

namespace MauiBuilder.Platforms.Android
{
    /// <summary>
    /// Android平台前台服务实现
    /// </summary>
    public class ForegroundServicePlatform : IForegroundService
    {
        private static bool _isServiceRunning = false;
        
        /// <summary>
        /// 服务状态变化事件
        /// </summary>
        public event Action<bool>? ServiceStateChanged;
        
        /// <summary>
        /// 日志管理器
        /// </summary>
        private readonly LogManager _logManager = LogManager.Instance;

        public ForegroundServicePlatform()
        {
            // 构造函数中同步初始状态
            SyncInitialServiceState();
        }
        
        /// <summary>
        /// 同步初始服务状态
        /// </summary>
        private void SyncInitialServiceState()
        {
            try
            {
                var serviceInstance = ForegroundService.GetServiceInstance();
                var actualServiceRunning = serviceInstance != null;
                
                if (_isServiceRunning != actualServiceRunning)
                {
                    _isServiceRunning = actualServiceRunning;
                    if (actualServiceRunning)
                    {
                        _logManager.LogInfo("检测到服务已运行，同步状态");
                        ServiceStateChanged?.Invoke(true);
                    }
                }
            }
            catch (Exception ex)
            {
                _logManager.LogError($"同步初始服务状态失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 检查前台服务权限
        /// </summary>
        /// <returns></returns>
        private bool CheckForegroundServicePermission()
        {
            var context = Platform.CurrentActivity ?? global::Android.App.Application.Context;
            
            if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.P)
            {
                return ContextCompat.CheckSelfPermission(context, Manifest.Permission.ForegroundService) == global::Android.Content.PM.Permission.Granted;
            }
            
            return true; // Android 9之前默认有前台服务权限
        }

        /// <summary>
        /// 请求前台服务权限
        /// </summary>
        private void RequestForegroundServicePermission()
        {
            if (Platform.CurrentActivity is AndroidX.Fragment.App.FragmentActivity activity)
            {
                if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.P)
                {
                    ActivityCompat.RequestPermissions(activity, new[] { Manifest.Permission.ForegroundService }, 1002);
                }
            }
        }

        /// <summary>
        /// 启动前台服务
        /// </summary>
        public async Task StartServiceAsync()
        {
            try
            {
                // 检查前台服务权限
                if (!CheckForegroundServicePermission())
                {
                    RequestForegroundServicePermission();
                    // 等待用户授权后再启动服务
                    _logManager.LogInfo("需要前台服务权限");
                    return;
                }
                
                var context = Platform.CurrentActivity ?? global::Android.App.Application.Context;
                var intent = new Intent(context, typeof(ForegroundService));
                
                // 使用 StartForegroundService 对于 Android 8.0 及以上版本
                if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.O)
                {
                    ContextCompat.StartForegroundService(context, intent);
                }
                else
                {
                    context.StartService(intent);
                }
                
                _isServiceRunning = true;
                ServiceStateChanged?.Invoke(true);
                _logManager.LogInfo("前台服务已启动");
            }
            catch (Exception ex)
            {
                _logManager.LogInfo($"启动前台服务失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 停止前台服务
        /// </summary>
        public async Task StopServiceAsync()
        {
            try
            {
                var context = Platform.CurrentActivity ?? global::Android.App.Application.Context;
                var intent = new Intent(context, typeof(ForegroundService));
                context.StopService(intent);
                
                _isServiceRunning = false;
                ServiceStateChanged?.Invoke(false);
                _logManager.LogInfo("前台服务已停止");
                
                await Task.CompletedTask;
            }
            catch (Exception ex)
            {
                _logManager.LogInfo($"停止前台服务失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 获取服务运行状态
        /// </summary>
        /// <returns>true表示服务正在运行，false表示服务已停止</returns>
        public bool IsServiceRunning()
        {
            // 检查实际的服务实例状态
            var serviceInstance = ForegroundService.GetServiceInstance();
            var actualServiceRunning = serviceInstance != null;
            
            // 如果发现状态不一致，更新本地状态
            if (_isServiceRunning != actualServiceRunning)
            {
                _isServiceRunning = actualServiceRunning;
                _logManager.LogInfo($"同步服务状态：{(actualServiceRunning ? "运行中" : "已停止")}");
                ServiceStateChanged?.Invoke(actualServiceRunning);
            }
            
            return _isServiceRunning;
        }
        
        /// <summary>
        /// 平台是否支持前台服务
        /// </summary>
        /// <returns>是否支持</returns>
        public bool IsForegroundServiceSupported()
        {
            return true; // Android 始终支持前台服务
        }
    }
}